package com.justech.eat.service.component.impl;

import com.justech.eat.entity.AccMonitorLog;
import com.justech.eat.entity.Order;
import com.justech.eat.entity.OrderDetail;
import com.justech.eat.repository.OrderDetailRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @program: eat-service
 * @description: 报餐结算
 * @author: feifei.li
 * @create: 2020-06-02 08:32
 * TODO 逻辑暂未写在此处
 **/

@Component
public class OrderSettlementTemplate {

    @Autowired
    OrderDetailRepository orderDetailRepository;

    /**
     * 获取所有用户用餐信息
     *
     * @param date
     * @return key：用户工号和就餐类别; value：就餐信息
     */
    Map<String, AccMonitorLog> getAccMonitorMap(String date) {
        return null;
    }

    public List<Order> getOrdersByDate(String date) {
        return null;
    }

    public void settlement(String date) {
        /*餐厅闸机的用餐数据*/
        Map<String, AccMonitorLog> accMonitorMap = getAccMonitorMap(date);

        /*预订数据*/
        List<Order> orders = getOrdersByDate(date);

        for (Order order : orders) {
            /*以订餐记录为基础数据结算*/
            settlementDetail(order, accMonitorMap);
            /*todo 以刷卡记录为基础结算*/
        }
    }

    public void settlementDetail(Order order, Map<String, AccMonitorLog> accMonitorMap) {
        List<OrderDetail> orderDetails = order.getOrderDetails();
        for (int i = 0; i < orderDetails.size(); i++) {
            OrderDetail orderDetail = orderDetails.get(i);
            Optional<OrderDetail> dbOrderDetail = orderDetailRepository.findById(orderDetail.getId());
            String remote = order.getJobNumber() + "_" + orderDetail.getType();
            AccMonitorLog accMonitorLog = accMonitorMap.get(remote);
            OrderDetail detail = dbOrderDetail.get();
            if (orderDetail.getStatus() == 1) {
                /*预订记录存在，说明餐厅闸机存在刷卡记录(订了也吃了)*/
                if (accMonitorLog != null) {
                    detail.setResult(1);
                } else {
                    /*不存在，则说明餐厅闸机不存在刷卡记录（订了没吃）*/
                    detail.setResult(2);
                }
            } else {
                /*吃了没订*/
                if (accMonitorLog != null) {
                    detail.setResult(3);
                }
            }

            detail.setFinal(true);
            orderDetail.setUpdateTime(new Date());
            orderDetail.setUpdateBy("定时计算任务");
            orderDetailRepository.saveAndFlush(orderDetail);
        }
    }

}
